package scripts

import (
	"bytes"
	"regexp"
	"github.com/jweny/pocassist/pkg/util"
	"strconv"
)

// exim远程调用
func EximOffByOneRCE(args *ScriptScanArgs) (*util.ScanResult, error) {
	versionPattern := regexp.MustCompile(`Exim (\d+\.\d+\.\d+|\d+\.\d+_\d+|\d+\.\d+)`)

	for _, port := range []int{25, 26, 465, 587} {
		target := args.Host+":"+strconv.Itoa(port)
		payload := "EHLO test\n"
		resp, err := util.TcpSend(target, []byte(payload))
		if port == 465 {
			resp, err = util.TcpTlsSend(target, []byte(payload))
		}
		if err != nil {
			continue
		}
		// 版本校验
		if resp != nil && bytes.Contains(resp, []byte("Exim")) {
			version := string(versionPattern.Find(resp))
			vul, err := util.SingleVersionCompare(version, "4.90.1")
			if err == nil && vul > 0{
				return util.VulnerableTcpOrUdpResult(target, "Version:"+version,[]string{payload}, []string{string(resp)}),nil
			}
		}
	}
	return &util.InVulnerableResult, nil
}

func init() {
	ScriptRegister("poc-go-exim-cve-2019-15846-rce", EximOffByOneRCE)
}
